package com.example.myapplication1.ui.profile;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.appcompat.app.AlertDialog;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.navigation.Navigation;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;

import com.example.myapplication1.LoginActivity;
import com.example.myapplication1.R;
import com.example.myapplication1.db.DatabaseHelper;
import com.example.myapplication1.utils.PreferenceManager;
import com.example.myapplication1.ui.order.OrderHistoryFragment;

// ChangePasswordFragment is in the same package, no need to import

public class ProfileFragment extends Fragment {
    private PreferenceManager preferenceManager;
    private TextView usernameText;
    private TextView phoneText;
    private TextView balanceText;
    private Button rechargeButton;
    private DatabaseHelper databaseHelper;
    private long userId;
    private double currentBalance;

    // 添加广播接收器用于接收余额更新
    private BroadcastReceiver balanceUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("balance_updated".equals(intent.getAction())) {
                updateBalance();
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        preferenceManager = new PreferenceManager(requireContext());
        databaseHelper = new DatabaseHelper(requireContext());
        userId = preferenceManager.getUserId();

        // 注册广播接收器
        LocalBroadcastManager.getInstance(requireContext())
            .registerReceiver(balanceUpdateReceiver, new IntentFilter("balance_updated"));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 注销广播接收器
        LocalBroadcastManager.getInstance(requireContext())
            .unregisterReceiver(balanceUpdateReceiver);
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        initViews(view);
        setupClickListeners(view);
        loadUserData();
        return view;
    }

    private void initViews(View view) {
        usernameText = view.findViewById(R.id.username_text);
        phoneText = view.findViewById(R.id.phone_text);
        balanceText = view.findViewById(R.id.balance_text);
        rechargeButton = view.findViewById(R.id.recharge_button);
    }

    private void setupClickListeners(View view) {
        // 充值按钮
        rechargeButton.setOnClickListener(v -> showRechargeDialog());

        // 个人信息
        view.findViewById(R.id.personal_info).setOnClickListener(v -> {
            // 使用Navigation组件导航到个人信息界面
            try {
                Navigation.findNavController(view).navigate(R.id.action_profile_to_personalInfo);
            } catch (Exception e) {
                // 如果没有定义相应的导航操作，使用传统方式
                Fragment fragment = new PersonalInfoFragment();
                requireActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.nav_host_fragment, fragment)
                    .addToBackStack(null)
                    .commit();
            }
        });

        // 密码修改
        view.findViewById(R.id.change_password).setOnClickListener(v -> {
            // 使用Navigation组件导航到密码修改界面
            try {
                Navigation.findNavController(view).navigate(R.id.action_profile_to_changePassword);
            } catch (Exception e) {
                // 如果没有定义相应的导航操作，使用传统方式
                Fragment fragment = new ChangePasswordFragment();
                requireActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.nav_host_fragment, fragment)
                    .addToBackStack(null)
                    .commit();
            }
        });

        // 订单记录
        view.findViewById(R.id.order_history).setOnClickListener(v -> {
            // 使用Navigation组件导航到订单记录界面
            try {
                Navigation.findNavController(view).navigate(R.id.action_profile_to_orderHistory);
            } catch (Exception e) {
                // 如果没有定义相应的导航操作，使用传统方式
                Fragment fragment = new OrderHistoryFragment();
                requireActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.nav_host_fragment, fragment)
                    .addToBackStack(null)
                    .commit();
            }
        });

        // 账号注销
        view.findViewById(R.id.delete_account).setOnClickListener(v -> {
            new AlertDialog.Builder(requireContext())
                .setTitle("账号注销")
                .setMessage("确定要注销账号吗？此操作不可恢复，您的所有数据将被彻底删除！")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 显示进度提示
                    Toast.makeText(requireContext(), "正在注销账号...", Toast.LENGTH_SHORT).show();
                    
                    // 删除用户及其所有关联数据
                    boolean deleted = databaseHelper.deleteUserAndRelatedData(userId);
                    
                    if (deleted) {
                        Toast.makeText(requireContext(), "账号已成功注销", Toast.LENGTH_SHORT).show();
                        // 清除会话信息
                        preferenceManager.clearSession();
                        // 返回登录页面
                        startLoginActivity();
                    } else {
                        Toast.makeText(requireContext(), "账号注销失败，请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
        });

        // 退出登录
        view.findViewById(R.id.logout).setOnClickListener(v -> {
            new AlertDialog.Builder(requireContext())
                .setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    preferenceManager.clearSession();
                    startLoginActivity();
                })
                .setNegativeButton("取消", null)
                .show();
        });

        // 紧急求助
        view.findViewById(R.id.emergency_help).setOnClickListener(v -> {
            new AlertDialog.Builder(requireContext())
                .setMessage("请尽快联系工作人员：\n\n13700000001\n13700000002\n13700000003")
                .setPositiveButton("确定", null)
                .show();
        });
    }

    private void loadUserData() {
        // 从PreferenceManager获取用户信息
        String username = preferenceManager.getUsername();
        String phone = preferenceManager.getPhone();
        updateBalance();

        // 更新UI
        usernameText.setText(username);
        phoneText.setText(phone);
    }

    // 更新余额显示
    private void updateBalance() {
        // 从数据库获取最新余额
        currentBalance = databaseHelper.getUserBalance(userId);
        // 更新SharedPreferences中的余额
        preferenceManager.setBalance(currentBalance);
        // 更新UI显示
        if (balanceText != null) {
            balanceText.setText(String.format("¥ %.2f", currentBalance));
        }
    }

    private void showRechargeDialog() {
        final Dialog dialog = new Dialog(requireContext());
        dialog.setContentView(R.layout.dialog_recharge);

        EditText amountInput = dialog.findViewById(R.id.recharge_amount);
        Button cancelButton = dialog.findViewById(R.id.btn_cancel);
        Button confirmButton = dialog.findViewById(R.id.btn_confirm);

        cancelButton.setOnClickListener(v -> dialog.dismiss());
        confirmButton.setOnClickListener(v -> {
            String amountStr = amountInput.getText().toString();
            if (amountStr.isEmpty()) {
                Toast.makeText(requireContext(), "请输入充值金额", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                double amount = Double.parseDouble(amountStr);
                if (amount <= 0) {
                    Toast.makeText(requireContext(), "请输入有效金额", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 更新数据库中的余额
                currentBalance += amount;
                if (databaseHelper.updateUserBalance(userId, currentBalance)) {
                    // 更新SharedPreferences中的余额
                    preferenceManager.setBalance(currentBalance);
                    // 更新UI显示
                    balanceText.setText(String.format("¥ %.2f", currentBalance));
                    dialog.dismiss();
                    Toast.makeText(requireContext(), "充值成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(requireContext(), "充值失败，请重试", Toast.LENGTH_SHORT).show();
                }
            } catch (NumberFormatException e) {
                Toast.makeText(requireContext(), "请输入有效金额", Toast.LENGTH_SHORT).show();
            }
        });

        dialog.show();
    }

    private void startLoginActivity() {
        Intent intent = new Intent(requireContext(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        requireActivity().finish();
    }
} 